<template>
  <el-input
    ref="filterText"
    v-model="searchTree"
    type="text"
    placeholder="请输入你要查询的权限"
  />
  <el-tree
    ref="treeRef"
    :data="TreeData"
    show-checkbox
    node-key="id"
    :props="defaultProps"
    :filter-node-method="filterNode"
    @check="handleClick"
  />
</template>
<script>
import { getAllListAPI } from "@/api/role";
import { deepTree } from "@/utils/deepMenu";
export default {
  props: ["checkedArr"],
  emits: ["checkTreeBox"],
  data: () => {
    return {
      searchTree: "", //存储查询用户权限字段
      defaultProps: {
        //树形数据默认属性值
        children: "children",
        label: "name",
      },
      //权限数据
      TreeData: [],
    };
  },
  mounted() {
    this.getAllList();
    this.setChecked();
  },
  watch: {
    searchTree: {
      handler(val) {
        this.$refs.treeRef?.filter(val);
      },
      immediate: true,
    },
  },
  methods: {
    //获取所有权限数据
    async getAllList() {
      const result = await getAllListAPI();
      //转换树形结构
      this.TreeData = deepTree(result);
    },

    //弹窗过滤
    filterNode(value, TreeData) {
      if (!value) return true;
      return TreeData.name?.includes(value); //TreeData.name是因为上面设置了label:"name"
    },

    //选中checkedKeys的id数组
    handleClick(value1, { checkedKeys }) {
      //把数据传给父组件
      this.$emit("checkTreeBox", checkedKeys);
    },

    //设置选中的权限框
    setChecked() {
      this.$refs.treeRef.setCheckedKeys(this.checkedArr);
    },
  },
};
</script>
